/*
 * Funny Language - a free style programming language.
 * Copyright (C) 2015 by fanguangping (fanguangping@163.com)
 * logfile.c
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>		// linux下头文件
#include "logfile.h"
#include "../base/utils.h"

#define FILE_MAX_SIZE (1024*1024)

/*
获得文件大小
@param filename [in]: 文件名
@return 文件大小
*/
long get_file_size(char* filename) {
	long length = 0;
	FILE *fp = NULL;

	fp = fopen(filename, "rb");
	if (fp != NULL) {
		fseek(fp, 0, SEEK_END);
		length = ftell(fp);
	}

	if (fp != NULL) {
		fclose(fp);
		fp = NULL;
	}

	return length;
}

/*
写入日志文件
@param filename [in]: 日志文件名
@param max_size [in]: 日志文件大小限制
@param buffer [in]: 日志内容
@param buf_size [in]: 日志内容大小
@return 空
*/
void write_log_file(char* filename, long max_size, char* buffer, unsigned buf_size) {
	if (filename != NULL && buffer != NULL) {
		// 文件超过最大限制, 删除
		long length = get_file_size(filename);

		if (length > max_size) {
			unlink(filename); // 删除文件
		}

		// 写日志
		{
			FILE *fp;
			fp = fopen(filename, "at+");
			if (fp != NULL) {
				char now[32];
				memset(now, 0, sizeof(now));
				get_local_time(now);
				fwrite(now, strlen(now), 1, fp);
				fwrite(buffer, buf_size, 1, fp);

				fclose(fp);
				fp = NULL;
			}
		}
	}
}

/*
int main(int argc, char** argv)
{
	int i;
	for (i=0; i<10; ++i)
	{
		char buffer[32];
		memset(buffer, 0, sizeof(buffer));
		sprintf(buffer, "====> %d\n", i);
		write_log_file("log.txt", FILE_MAX_SIZE, buffer, strlen(buffer));

	}
	// system("pause");
	return 0;
}
*/

void log_string(String prefix, String s) {
#ifdef DEBUG_FLAG
	char buffer[1024];
	memset(buffer, 0, sizeof(buffer));
	sprintf(buffer, "%s: %s\n", prefix, s);
	write_log_file("funny.log", FILE_MAX_SIZE, buffer, strlen(buffer));
#endif
}

void log_cell(Scheme* sc, Cell *cell) {
#ifdef DEBUG_FLAG
	char buffer[1024];
	memset(buffer, 0, sizeof(buffer));
	sprintf(buffer, "[Cell]: %s\n", cell2str(sc, cell));
	write_log_file("funny.log", FILE_MAX_SIZE, buffer, strlen(buffer));
#endif
}

void log_statement(Statement *s) {
#ifdef DEBUG_FLAG
	char buffer[1024];
	memset(buffer, 0, sizeof(buffer));
	sprintf(buffer, "[Statement]: %s\n", to_string_statement(s));
	write_log_file("funny.log", FILE_MAX_SIZE, buffer, strlen(buffer));
#endif
}

void log_mapping(Mapping *m) {
#ifdef DEBUG_FLAG
	char buffer[1024];
	memset(buffer, 0, sizeof(buffer));
	//sprintf(buffer, "[Mapping]: %s\n", to_string_statement(s));
	write_log_file("funny.log", FILE_MAX_SIZE, buffer, strlen(buffer));
#endif
}
